import 'dart:convert';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:cave_flutter/config/whl_base_controller.dart';
import 'package:cave_flutter/model/whl_user_info_model.dart';
import 'package:cave_flutter/network/whl_network_utils.dart';
import 'package:cave_flutter/pages/whl_login/view/whl_login_agreement_dialog.dart';
import 'package:cave_flutter/utils/whl_current_limiting_util.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';

import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/services.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:get/get.dart';
import 'package:quickpass_yidun_flutter/quickpass_flutter_plugin.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:video_player/video_player.dart';

import '../../common/common_action.dart';
import '../../model/base_model.dart';
import '../../network/whl_api.dart';
import '../../routes/whl_app_pages.dart';
import '../../utils/whl_permission_util.dart';

class WhlLoginLogic extends WhlBaseController {
  bool agreePrivateStatus = false;
  /// 统一 key
  final String f_result_key = "success";

  List<BaseModel> loginTypeList = [
    BaseModel(icon: 'icon_login_wechat.png', loginType: LoginType.wechat),
    BaseModel(icon: 'icon_login_qq.png', loginType: LoginType.qq),
    BaseModel(icon: 'icon_login_weibo.png', loginType: LoginType.weibo),
  ];

  final QuickpassFlutterPlugin quickLoginPlugin = QuickpassFlutterPlugin();
  late VideoPlayerController videoPlayerController;

  // late AMapFlutterLocation flutterLocation;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    videoPlayerController = VideoPlayerController.networkUrl(Uri.parse('http://app.cave-meta.com:9010/video/mobile.mp4'))
    ..initialize().then((_) {
        print("video 初始化成功");
        update();
      })
    ..setLooping(true)..setVolume(0)..play();
    quickLoginPlugin.checkVerifyEnable().then((map) {
      bool result = map?['success'];
      if (result){
        print("能一键登录");
      }else {
        print("不能一键登录");
      }
    });
    quickLoginPlugin.init("c3e5fb1edac24b1bb2b57e926a57b1c4",60,true).then((value) {
      bool result = value?[f_result_key]??false;
      if (result){
        print("一键登录SDK初始化成功");
      }else {
        print("一键登录SDK初始化失败");
      }
      getQuickLoginPhone();
    });

    // AMapFlutterLocation.updatePrivacyShow(true, true);
    // AMapFlutterLocation.updatePrivacyAgree(true);
    // flutterLocation = AMapFlutterLocation();
    //
    // WhlPermissionUtil.reqLocationWhenInUsePermission(
    //     onSuccessAction: (){
    //
    //       flutterLocation.startLocation();
    //     }
    // );
    //
    // flutterLocation.onLocationChanged().listen((event) {
    //   print("定位结果");
    //   print(event);
    // });
    // flutterLocation.startLocation();
  }

  getQuickLoginPhone() async {
    Map map = await quickLoginPlugin.preFetchNumber()??{};
    print("预取号");
    print(map);
    if (map['success'] == true) {
      var ydToken = map['token'];
      //{ydToken: 5f7ef0a3c39f4f82bf8262b268c96e25, success: true,
      // accessToken: tdE3xWsUmL6R7ububiYCYWOvGxvAIYTvRAHBXf2_Z38UDCk6lSECtfjb7ex1UxnwTPBuUb5Cfx2qjqWMUdOnx5JCR_qhrdSpiF16o21TSwiae42nhmBSqJ1KhjfrOTlcvchu9Dy04hv-k3Jw8iIo-ytGU2jyLqwp76PK9ighdyUJwI0hz8D0jWbyCvrk_fLjikOHzV9Cum-lCzZUHDeR2Tkei6PN9lIosmV1hEViOMesZlU5_Nhqf0Ue_r4j_un5kxTuTxlEKiccL20d2FZoD3wivZZnEg5L9DuiKt-KOFmLWJD-H55lMx_u_twGtknB6_4=}
    } else {
      var ydToken = map['token'];
      var errorMsg = map['errorMsg'];
    }
  }

  quickLoginRequest(String accessToken,String token){
    BotToast.showLoading();
    WhlApi.fastLogin.post({"accessToken":accessToken,"token":token}).then((value) {
      if (value.isSuccess()){
        String token = value.data["token"];
        WhlNetWorkUtils.setAccessToken(token);
        // Get.offNamed(Routes.main);
        getUserInfo(isLogin: true,callback: (isSuccess){
          BotToast.closeAllLoading();
          if (!isSuccess) {
            MyToast.show("获取用户信息失败");
          }
        });
      }else {
        BotToast.closeAllLoading();
      }
    });
  }

  void doClickAppleLogin() async {
    if (!agreePrivateStatus) {
      Get.dialog(WhlLoginAgreementDialog(
        onTagAgree: () {
          Get.back();
          agreePrivateStatus = true;
          update();
          WhlCurrentLimitingUtil.debounce(() {
            onAppleLogin();
          });
        },
      ));
      return;
    }
    WhlCurrentLimitingUtil.debounce(() {
      onAppleLogin();
    });
  }

  doClickFastLogin() async {
    if (!agreePrivateStatus) {
      Get.dialog(WhlLoginAgreementDialog(
        onTagAgree: () {
          Get.back();
          agreePrivateStatus = true;
          update();
          WhlCurrentLimitingUtil.debounce(() {
            onFastLogin();
          });
        },
      ));
      return;
    }
    WhlCurrentLimitingUtil.debounce(() {
      onFastLogin();
    });
  }

  onAppleLogin() async {
    Get.offAllNamed(Routes.main);
    return;
    // final credential = await SignInWithApple.getAppleIDCredential(
    //   scopes: [
    //     AppleIDAuthorizationScopes.email,
    //     AppleIDAuthorizationScopes.fullName,
    //   ],
    // );
    // Map<String, dynamic> params = {
    //   'oauthType': 3,
    //   'token': credential.identityToken,
    // };
    // // Get.offAndToNamed(Routes.main);
    // ResponseData responseData = await WhlApi.userLogin.post(params, isJson: false);
    // if (responseData.isSuccess()) {
    //   onLoginSuccess(responseData);
    // }
  }

  onFastLogin() async {
    quickLoginPlugin.checkVerifyEnable().then((map) {
      bool result = map?['success'];
      if (result){
        // print("能一键登录");
      }else {
        // print("不能一键登录");
        MyToast.show("一键登录失败，未检测到SIM卡");
      }
    });

    String file = "";
    if (Platform.isIOS) {
      file = "asserts/ios-light-config.json";
    } else if (Platform.isAndroid) {
      file = "asserts/android-light-config.json";
    }
    rootBundle.loadString(file).then((value) async {
      print(value);
      print(1111111);
      Map configMap = {"uiConfig": json.decode(value)};
      quickLoginPlugin.setUiConfig(configMap);
      // 拉起授权页面
      Map map = await quickLoginPlugin.onePassLogin(animated: true)??{};
      print("拉起授权页面");
      print(map);
      if (map["success"]) {
        var accessToken = map["accessToken"];
        var ydToken = map["ydToken"];
        quickLoginRequest(accessToken, ydToken);
      } else {
        var errorMsg = map["msg"];
      }
      quickLoginPlugin.closeLoginAuthView();
    });

    // BotToast.showLoading();
    // Map<String, dynamic> params = {
    //   'oauthType': 4,
    //   'token': await FlutterUdid.udid,
    // };
    // // Get.offAndToNamed(Routes.main);
    // // ResponseData responseData = await WhlApi.userLogin.post(params, isJson: false);
    // // if (responseData.isSuccess()) {
    // //   onLoginSuccess(responseData);
    // // }
    // BotToast.closeAllLoading();
  }

  onLoginSuccess(ResponseData responseData) async {
    WhlNetWorkUtils.setAccessToken(responseData.data['token']);
    WhlUserInfoModel userInfoModel = WhlUserInfoModel.fromJson(responseData.data['userInfo']);
    String token = responseData.data['token'];
    WhlNetWorkUtils.setAccessToken(token);
    WhlUserUtils.saveUserInfo(userInfoModel);
    await WhlDBUtils().initDB();
    Get.offAndToNamed(Routes.main);
  }

  doClickSelect() {
    agreePrivateStatus = !agreePrivateStatus;
    update();
  }

  void thirdLogin() {
    print("third login");
  }

// doClickTermsOfUse() {
//   Get.toNamed(WhlRoutes.webView, arguments: {'webUrl': WhlApi.termConditions, 'title': 'Terms of Use'});
// }
//
// doClickPrivacyPolicy() {
//   Get.toNamed(WhlRoutes.webView, arguments: {'webUrl': WhlApi.privacyPolicy, 'title': 'Privacy Policy'});
// }
}
